package com.nowcoder.community.community.service;

import com.nowcoder.community.community.dao.LoginTicketMapper;
import com.nowcoder.community.community.dao.UserMapper;
import com.nowcoder.community.community.entity.LoginTicket;
import com.nowcoder.community.community.entity.User;
import com.nowcoder.community.community.util.sensitiveFilter;
import com.nowcoder.community.community.util.CommunityConstant;
import com.nowcoder.community.community.util.CommunityUtil;
import com.nowcoder.community.community.util.MailClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Service
public class UserService implements CommunityConstant {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MailClient mailClient;

    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private LoginTicketMapper loginTicketMapper;

    @Autowired
    private sensitiveFilter sensitiveFilter;

//    项目地址
    @Value("${community.path.domain}")
    private String domain;

//    主机访问目录
    @Value("${server.servlet.context-path}")
    private String contextPath;

    public User findUserById(int id){
        return userMapper.selectById(id);
    }

//    注册
    public Map<String, Object> register(User user){
        HashMap<String, Object> map = new HashMap<>();

        //null处理
        if(user == null){
            throw new IllegalArgumentException("参数不能为空！");
        }
        if(StringUtils.isBlank(user.getUsername())){
            map.put("usernameMsg","账号名不能为空");
            return map;
        }
        if(StringUtils.isBlank(user.getPassword())){
            map.put("passwordMsg","密码不能为空！");
            return map;
        }
        if(StringUtils.isBlank(user.getEmail())){
            map.put("emailMsg","邮箱不能为空！");
            return map;
        }
        //检测是否具有敏感词汇
        if(!sensitiveFilter.isAcceptable(user.getUsername())){
            map.put("usernameMsg","账号名不合法！");
            return map;
        }

        //验证账号
        User user1 = userMapper.selectByName(user.getUsername());
        if(user1 != null){
            map.put("usernameMsg","该账号名已存在！");
            return map;
        }

        //验证邮箱
        User user2 = userMapper.selectByEmail(user.getEmail());
        if(user2 != null){
            map.put("emailMsg","该邮箱已注册！");
            return map;
        }

        //注册用户  加盐 MD5加密
        user.setSalt(CommunityUtil.generateUUID().substring(0,5));
        user.setPassword(CommunityUtil.MD5(user.getPassword()+user.getSalt()));
        user.setStatus(0);
        user.setType(0);
        user.setActivationCode(CommunityUtil.generateUUID());
        user.setHeaderUrl(String.format(("http://images.nowcoder.com/head/%dt.png"), new Random().nextInt(1000)));
        user.setCreateTime(new Date());
        userMapper.insertUser(user);

        //获取激活码
        Context context = new Context();
        context.setVariable("email",user.getEmail());
        //http://localhost:8080/community/activation/101/code
        String url = domain + contextPath + "/activation/" + user.getId() + "/" + user.getActivationCode();
        context.setVariable("url",url);
        String content = templateEngine.process("/mail/activation",context);
        Thread sendmail = new Thread(()->{
            mailClient.sendMail(user.getEmail(), "激活账号", content);
        });
        sendmail.start();
        return map;
    }

//    激活是否成功
    public int activation(int userId, String code){
        User user = userMapper.selectById(userId);
        if (user.getStatus()==1){
            return ACTIVATION_REPRAT;
        }else if(user.getActivationCode().equals(code)){
            userMapper.updateStatus(userId,1);
            return ACTVATION_SUCCESS;
        }else {
            return ACTIVATION_FAILED;
        }
    }

//    登陆情况
    public Map<String, Object> login(String username, String password, int expiredSeconds){
        Map<String, Object> map = new HashMap<>();

        //空值处理
        if(StringUtils.isBlank(username)){
            map.put("usernameMsg","账号不能为空！");
            return map;
        }
        if(StringUtils.isBlank(password)){
            map.put("passwordMsg","密码不能为空！");
            return map;
        }

        //验证账号
        User user = userMapper.selectByName(username);
        if (user == null){
            map.put("usernameMsg","该账号不存在！");
            return map;
        }

        //验证激活状态
        if(user.getStatus() == 0){
            map.put("usernameMsg","该账号未激活！");
            return map;
        }

        //验证密码
        password = CommunityUtil.MD5(password + user.getSalt());
        if(!user.getPassword().equals(password)){
            map.put("passwordMsg","密码不正确！");
            return map;
        }

        //生成登陆凭证
        LoginTicket loginTicket = new LoginTicket();
        loginTicket.setUserId(user.getId());
        loginTicket.setTicket(CommunityUtil.generateUUID());
        loginTicket.setStatus(0);
        loginTicket.setExpered(new Date(System.currentTimeMillis() + expiredSeconds * 1000));
        loginTicketMapper.insertLoginTictet(loginTicket);

        map.put("ticket",loginTicket.getTicket());

        return map;
    }
//    退出
    public void logout(String ticket){
        loginTicketMapper.updateStatus(ticket,1);
    }

    public void login(String ticket){
        loginTicketMapper.updateStatus(ticket,0);
    }

//    获取loginticket
    public LoginTicket findLoginTicket(String ticket){
        return loginTicketMapper.selectByTicket(ticket);
    }

//    更新用户头像
    public int updateHeader(int userId,String headerUrl){
        return userMapper.updateHeader(userId,headerUrl);
    }

//    更新用户名
    public Map<String, Object> upadeUserName(int userId, String userName){
        Map<String, Object> map = new HashMap<>();
        if(userName == null || StringUtils.isBlank(userName)){
            return map;
        }
        //用户名非空，判断是否合法和重复
        if(!sensitiveFilter.isAcceptable(userName)){
            map.put("usernameMsg","该账户名不合法！");
            return map;
        }

        User user = userMapper.selectByName(userName);
        if (user == null){
            userMapper.upadeUserName(userId,userName);
        }else {
            map.put("usernameMsg","该账号名已存在！");
        }
        return map;
    }

//    更新密码
    public Map<String, Object> updatePassword(int userId,String oldPassword,String newPassword){
        Map<String, Object> map = new HashMap<>();
        User user = userMapper.selectById(userId);
        if(StringUtils.isBlank(oldPassword)){
            map.put("oldPasswordMsg","原密码不能为空！");
            return map;
        }
        if(!CommunityUtil.MD5(oldPassword+user.getSalt()).equals(user.getPassword())){
            map.put("oldPasswordMsg","密码输入错误，与原密码不相同！");
            return map;
        }
        if(StringUtils.isBlank(newPassword)){
            map.put("newPasswordMsg","密码不能为空！");
            return map;
        }

        //没有问题开始修改密码
        newPassword = CommunityUtil.MD5(newPassword + user.getSalt());
        userMapper.updatePassword(userId,newPassword);
        return map;
    }

//    通过用户名获取用户
    public User findUserByName(String username){
        return userMapper.selectByName(username);
    }
}
